package org.shopping.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * druid连接池
 */
public class JDBCUtils2 {

    private JDBCUtils2(){}

    private static DataSource dataSource = null;

    static {

        try {
            // 创建配置文件对象
            Properties properties = new Properties();
            // 获取输入流
            ClassLoader classLoader = JDBCUtils2.class.getClassLoader();
            InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties");
            // 加载配置文件
            properties.load(resourceAsStream);
            // 通过druidFactory获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 从连接池里获取连接对象
     * @return 连接对象
     */
    public static Connection getConnectionFromPool() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void closeResources(Connection con, Statement stmt, ResultSet rs) {
        // 关闭资源
        try {
            if(con != null){
                con.close();
            }
            if(stmt != null){
                stmt.close();
            }
            if(rs != null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
